<?php

session_start();
include_once($_SERVER['DOCUMENT_ROOT'] ."/include/user/inc.php");
include_once($_SERVER['DOCUMENT_ROOT'] ."/include/mblog/inc.php");
include_once( 'config.php' );
include_once( 'saetv2.ex.class.php' );

$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );

if (isset($_REQUEST['code'])) {
	$keys = array();
	$keys['code'] = $_REQUEST['code'];
	$keys['redirect_uri'] = WB_CALLBACK_URL;
	try {
		$token = $o->getAccessToken( 'code', $keys ) ;
	} catch (OAuthException $e) {
	}
}

if ($token) {
	
	$db_user_token = new db_user_token();
	$uid = $token["uid"];
	$access_token = $token["access_token"] ;
	$expires_in = $token["expires_in"] ;
	$refresh_token = $token["refresh_token"] ;
	$remind_in = $token["remind_in"] ;
	if($uid)
	{
		$res = $db_user_token->insert_user_token($uid,WB_AKEY,$access_token,$version=2,$expires_in,$refresh_token,$remind_in);
	}
	
	
	$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $token["access_token"] );
	$current_uid = $uid;
	
	$user_pic = "/images/user_icon/default/default_1.jpg";
	$user_info = new user_info();
	
	$db_user_info = new db_user_info();
	$user_item =  $db_user_info->get_user_item_by_name($current_uid);
	if(!$user_item)
	{
		try 
		{
			$insert_uid= $user_info->insert_user_info($current_uid,$current_uid,$user_pic);
		}
		catch (Exception $e)
		{
		}
		
	}
	if($user_item["uid"])
	{
		$insert_uid = $user_item["uid"];
	}
	
	
	
	$set_cookie_res= $user_info->set_cookie_by_user_info($insert_uid,$current_uid);
	
	//必须放在后面 会清一次cookie
	$_SESSION['token'] = $token;
	setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
	
	
	header("Location:/mblog/fanlaji/at_res.php");
	
}
